<?php
require_once 'libs/auth.class.php';
require_once 'libs/mysql.class.php';
require_once 'libs/tableManager.class.php';

$conn = new Mysql();
$auth = new Auth();

if ( !$auth->is_connected() ) {
	header('Location: login.php');
	exit();
}

require_once 'libs/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
		/*'cache' => '/path/to/compilation_cache',*/
));

$tplVars = array();

$tplVars['breadcrumb'][] = array('caption' => 'Dashboard','href' => 'index.php','curr' => false,);
$tplVars['breadcrumb'][] = array('caption' => 'Cabinet','href' => 'cabinet.php','curr' => false,);
$tplVars['breadcrumb'][] = array('caption' => 'New','href' => 'cabinet.php','curr' => true,);

$tplVars['jsFiles'] = array(
	'bootstrap/js/jquery.min.js',
	'bootstrap/js/jquery.ui.custom.js',
    'bootstrap/js/bootstrap.min.js',
    'bootstrap/js/bootstrap-colorpicker.js', 
    'bootstrap/js/bootstrap-datepicker.js', 
    'bootstrap/js/jquery.uniform.js',
    'bootstrap/js/select2.min.js',
	'bootstrap/js/unicorn.js',
	'bootstrap/js/unicorn.tables.js',
);

$tableName = $_REQUEST['table'];

$tableManager = new TableManager($tableName);

if ( isset($_REQUEST['submit']) && $_REQUEST['submit'] == 'submit' ) {
    if ( $_REQUEST['action'] == 'insert' ) {
        $tableManager->insert($tableName);
    }
    elseif ( $_REQUEST['action'] == 'update' ) {
        $pKeys = $tableManager->getPrimaryKeys($tableName);
        foreach( $pKeys as $pKey ) {
            $whereArray[$pKey] = $_GET['p'];
        }
        $tableManager->update($tableName, $whereArray);
        header("Location: $tableName.php");
        exit();
    }
}


$whereArray = array();
if ( $_GET['p'] != '' ) {
    $pKeys = $tableManager->getPrimaryKeys($tableName);
    foreach( $pKeys as $pKey ) {
        $whereArray[$pKey] = $_GET['p'];
    }
}

if ( empty($whereArray) ) {
    $tplVars['action'] = 'insert';
    $nextAI = $conn->GetNextAutoIncrement($tableName);
    $tplVars['next_AI'] = $nextAI;
    
    $datas = $tableManager->getStructureTable( $tableName );
}
else {
    $tplVars['action'] = 'update';
    $sql   = $conn->BuildSQLSelect($tableName, $whereArray);
    $datas = $tableManager->getDatas($tableName, $sql);
}



$tplVars['tableName'] = $tableName;
$tplVars['inputs'] = $datas;

echo $twig->render('forms.twig', $tplVars);